/**
 * 583. 两个字符串的删除操作
 */
public class No583 {
    private String word1, word2;

    /**
     * 1. 递归
     */
    public int minDistance1(String word1, String word2) {
        this.word1 = word1;
        this.word2 = word2;
        int n = word1.length();
        int m = word2.length();
        return dfs(n - 1, m - 1);
    }

    private int dfs(int i, int j) {
        if (i < 0) return j + 1;
        if (j < 0) return i + 1;
        if (word1.charAt(i) == word2.charAt(j)) return dfs(i - 1, j - 1);
        else return Math.min(dfs(i - 1, j), dfs(i, j - 1)) + 1;
    }

    /**
     * 2. 迭代
     */
    public int minDistance2(String word1, String word2) {
        int n = word1.length();
        int m = word2.length();

        int[][] f = new int[n + 1][m + 1];
        for (int j = 1; j < f[0].length; j++) {
            f[0][j] = j;
        }
        for (int i = 0; i < n; i++) {
            f[i + 1][0] = i + 1;
            for (int j = 0; j < m; j++) {
                if (word1.charAt(i) == word2.charAt(j)) f[i + 1][j + 1] = f[i][j];
                else f[i + 1][j + 1] = Math.min(f[i][j + 1], f[i + 1][j]) + 1;
            }
        }
        return f[n][m];
    }

    /**
     * 3. 滚动数组
     */
    public int minDistance3(String word1, String word2) {
        int n = word1.length();
        int m = word2.length();

        int[][] f = new int[2][m + 1];
        for (int j = 1; j < f[0].length; j++) {
            f[0][j] = j;
        }
        for (int i = 0; i < n; i++) {
            f[(i + 1) % 2][0] = i + 1;
            for (int j = 0; j < m; j++) {
                if (word1.charAt(i) == word2.charAt(j)) f[(i + 1) % 2][j + 1] = f[i % 2][j];
                else f[(i + 1) % 2][j + 1] = Math.min(f[i % 2][j + 1], f[(i + 1) % 2][j]) + 1;
            }
        }
        return f[n % 2][m];
    }

    /**
     * 4. 一维数组
     */
    public int minDistance4(String word1, String word2) {
        int n = word1.length();
        int m = word2.length();

        int[] f = new int[m + 1];
        for (int j = 1; j < m + 1; j++) {
            f[j] = j;
        }
        for (int i = 0; i < n; i++) {
            int pre = f[0]; // 保留上一个变量
            f[0] = i + 1;
            for (int j = 0; j < m; j++) {
                int temp = f[j + 1];
                if (word1.charAt(i) == word2.charAt(j)) f[j + 1] = pre;
                else f[j + 1] = Math.min(f[j + 1], f[j]) + 1;
                pre = temp;
            }
        }
        return f[m];
    }
}
